package city.spring.modules.oldman.controller;

import city.spring.modules.oldman.entity.VisitingEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.oldman.service.VisitingService;
import city.spring.modules.oldman.vo.VisitingVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：探视来访
 *
 * @author 谢金婷
 * @date 2020-04-14 16:27:48
 */
@RestController
@RequestMapping("/visiting")
public class VisitingController extends ApiController {
    private final VisitingService visitingService;
    private final OldmanInfoService oldmanInfoService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<VisitingEntity, ?>> entityOrderFields;

    public VisitingController(VisitingService visitingService, OldmanInfoService oldmanInfoService) {
        this.visitingService = visitingService;
        this.oldmanInfoService = oldmanInfoService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(VisitingEntity::getId);
        entityOrderFields.add(VisitingEntity::getVisitor);
        entityOrderFields.add(VisitingEntity::getOldmanId);
        entityOrderFields.add(VisitingEntity::getTelephone);
        entityOrderFields.add(VisitingEntity::getRelationshipOldman);
        entityOrderFields.add(VisitingEntity::getVisitDate);
        entityOrderFields.add(VisitingEntity::getRegister);
        entityOrderFields.add(VisitingEntity::getReason);
        entityOrderFields.add(VisitingEntity::getRemark);
        entityOrderFields.add(VisitingEntity::getDepartureDate);
    }

    /**
     * 获取全部的 <strong>探视来访</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, VisitingEntity entity) {
        LambdaQueryChainWrapper<VisitingEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>探视来访</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, VisitingVO entity, Date[] visitDate, Date[] departureDate) {
        QueryWrapper<? extends VisitingEntity> queryWrapper = buildQuery(entity);

        if (visitDate != null && visitDate.length == 2) {
            queryWrapper.ge("t1.visit_date", visitDate[0]);
            queryWrapper.le("t1.visit_date", visitDate[1]);
        }
        if (departureDate != null && departureDate.length == 2) {
            queryWrapper.ge("t1.departure_date", departureDate[0]);
            queryWrapper.le("t1.departure_date", departureDate[1]);
        }

        return success(visitingService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>探视来访</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        Page<VisitingVO> page = new Page<>();
        QueryWrapper<VisitingVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        IPage<VisitingVO> iPage = visitingService.listPage(page, wrapper);
        List<VisitingVO> records = iPage.getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>探视来访</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody VisitingEntity entity) {
        visitingService.saveVisiting(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>探视来访</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody VisitingEntity entity) {
        entity.setId(id);
        visitingService.updateVisiting(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 设置一个 <strong>探视来访</strong> 的离开时间
     *
     * @param id 主键ID
     */
    @PutMapping("{id}/leave")
    public Object update(@PathVariable String id) {
        visitingService.lambdaUpdate()
                .eq(VisitingEntity::getId, id)
                .isNull(VisitingEntity::getDepartureDate)
                .set(VisitingEntity::getDepartureDate, new Date())
                .update();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>探视来访</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        visitingService.deleteVisiting(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>探视来访</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        visitingService.deleteVisiting(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<VisitingEntity> buildLambdaQuery(VisitingEntity entity) {
        LambdaQueryChainWrapper<VisitingEntity> lambdaQuery = visitingService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), VisitingEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getVisitor()), VisitingEntity::getVisitor, entity.getVisitor());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getOldmanId()), VisitingEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTelephone()), VisitingEntity::getTelephone, entity.getTelephone());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRelationshipOldman()), VisitingEntity::getRelationshipOldman, entity
                .getRelationshipOldman());
        lambdaQuery.like(entity.getVisitDate() != null, VisitingEntity::getVisitDate, entity.getVisitDate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRegister()), VisitingEntity::getRegister, entity.getRegister());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReason()), VisitingEntity::getReason, entity.getReason());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRemark()), VisitingEntity::getRemark, entity.getRemark());
        lambdaQuery.like(entity.getDepartureDate() != null, VisitingEntity::getDepartureDate, entity.getDepartureDate());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query wrapper
     */
    private QueryWrapper<? extends VisitingEntity> buildQuery(VisitingVO entity) {
        QueryWrapper<? extends VisitingEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.eq(StringUtils.isNotBlank(entity.getOldmanId()), "t1.oldman_id", entity.getOldmanId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanName()), "t2.oldman_name", entity.getOldmanName());
        wrapper.like(StringUtils.isNotBlank(entity.getVisitor()), "t1.visitor", entity.getVisitor());
        wrapper.like(StringUtils.isNotBlank(entity.getTelephone()), "t1.telephone", entity.getTelephone());
        wrapper.like(StringUtils.isNotBlank(entity.getRelationshipOldman()), "t1.relationship_oldman", entity.getRelationshipOldman());
        wrapper.eq(entity.getVisitDate() != null, "t1.visit_date", entity.getVisitDate());
        wrapper.like(StringUtils.isNotBlank(entity.getRegister()), "t1.register", entity.getRegister());
        wrapper.like(StringUtils.isNotBlank(entity.getReason()), "t1.reason", entity.getReason());
        wrapper.like(StringUtils.isNotBlank(entity.getRemark()), "t1.remark", entity.getRemark());
        wrapper.eq(entity.getDepartureDate() != null, "t1.departure_date", entity.getDepartureDate());
        return wrapper;
    }
}
